<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/8/14
 * Time: 19:26
 */

namespace frontend\modules\v1\controllers;


use Yii;
use frontend\modules\v1\models\RegisterForm;
use frontend\modules\v1\models\LoginForm;
use frontend\controllers\BaseController;
use frontend\modules\v1\models\ResetPasswordForm;
use common\models\Business;
use yii\db\Query;

/**
 * 前台相关接口
 * Class RegisterController
 * @package frontend\modules\v1\controllers
 */
class RegisterController extends BaseController {

    /**
     * 注册接口
     * @param account 账号(手机号)
     * @param code 验证码
     * @param password 密码
     * @param repassword 确认密码
     */
    public function actionSignup()
    {
        /** 校验表单是否为空 */
        if(!$this->postData){
            $this->responseError("参数信息为空.");
        }
        /** 定义返回数据 */
        $resultData = array();
        /** 接收表单参数 */
        $registerForm = new RegisterForm();
        $registerForm->account = $this->postData['account'];
        $registerForm->code = $this->postData['code'];
        $registerForm->password = $this->postData['password'];
        $registerForm->repassword = $this->postData['repassword'];

        /** 校验验证码 */
        $query = new Query();
        $data = $query->select(['code','created_at'])->from('code')
            ->where(['and', 'mobile=' . $registerForm->account])
            ->orderBy(['id' => SORT_DESC])
            ->limit(1)
            ->all();
        Yii::error("data = " . json_encode($data));
        if($data){
            $data = $data[0];
            $createAt = $data['created_at'] + 60;
            $d = time();
//            error_log("createAt = " . $createAt . "\n", 3, "/tmp/rjl.log");
//            error_log("d = " . $d . "\n", 3, "/tmp/rjl.log");
//            error_log("code = " . $data['code'] . "\n", 3, "/tmp/rjl.log");
//            error_log("form code = " . $registerForm->code . "\n", 3, "/tmp/rjl.log");
            if($createAt < $d){
                return $this->responseError(10005, "code is timeout.");
            }
            if(intval($data['code']) != intval($registerForm->code)){
                return $this->responseError(10006, "code info is error.");
            }
        }else{
            return $this->responseError(10007, "code is null.");
        }

        /** 注册 */
        if($business = $registerForm->signup()){
            /** 成功返回 */
            $resultData['id'] = $business->getId();
            $resultData['auth_key'] = $business->getAuthKey();
            return $this->responseFormat($resultData);
        }
        /** 失败返回 */
        if($registerForm->errors){
            foreach($registerForm->errors as $key=>$info ){
                $resultData[$key] = $info;
            }
        }
        return $this->responseError($resultData);
    }

    /**
     * 登陆接口
     * @param account 账号
     * @param password 密码
     * @param rememberMe 是否自动登陆 1是 0否
     */
    public function actionLogin()
    {
        /** 校验表单是否为空 */
        if(!$this->postData){
            $this->responseError("参数信息为空.");
        }
        /** 定义返回数据 */
        $resultData = array();
        /** 接收登陆数据 */
        $loginForm = new LoginForm();
        $loginForm->account = $this->postData['account'];
        $loginForm->password = $this->postData['password'];
        $loginForm->rememberMe = intval($this->postData['rememberMe']) == 1 ? true : false;

        /** 登陆 */
        $bool = $loginForm->login();
        if($bool){
            /** 成功返回 */
            $resultData['id'] = $loginForm->getBusiness()->getId();
            $resultData['auth_key'] = $loginForm->getBusiness()->getAuthKey();
            $resultData['status'] = $loginForm->getBusiness()->status;
            return $this->responseFormat($resultData);
        }

        /** 失败返回 */
        if($loginForm->errors){
            foreach($loginForm->errors as $key=>$info ){
                $resultData[$key] = $info;
            }
        }
        return $this->responseError($resultData);
    }

    /**
     * 忘记密码接口
     * @param account 账号(手机号)
     * @param code 验证码
     * @param password 密码
     * @param repassword 确认密码
     */
    public function actionResetpassword()
    {
        /** 校验表单是否为空 */
        if(!$this->postData){
            $this->responseError("参数信息为空.");
        }
        /** 定义返回数据 */
        $resultData = array();

        /** 接收表单参数 */
        $resetPasswordForm = new ResetPasswordForm();
        $resetPasswordForm->account = $this->postData['account'];
        $resetPasswordForm->code = $this->postData['code'];
        $resetPasswordForm->password = $this->postData['password'];
        $resetPasswordForm->repassword = $this->postData['repassword'];

        /** 校验验证码 */
        $query = new Query();
        $data = $query->select(['code','created_at'])->from('code')
            ->where(['and', 'mobile=' . $resetPasswordForm->account])
            ->orderBy(['id' => SORT_DESC])
            ->limit(1)
            ->all();
        if($data){
            $data = $data[0];
            $createAt = $data['created_at'] + 60;
            $d = time();
            if($createAt < $d){
                return $this->responseError(10005, "code is timeout.");
            }
            if(intval($data['code']) != intval($registerForm->code)){
                return $this->responseError(10006, "code info is error.");
            }
        }else{
            return $this->responseError("code info is wrong.");
        }

        /** 重置密码 */
        $bool = $resetPasswordForm->resetPassword();
        if ($bool) {
            $loginForm = new LoginForm();
            $loginForm->account = $this->postData['account'];
            $loginForm->password = $this->postData['password'];
            $loginForm->rememberMe = true;
            /** 登陆 */
            $bool = $loginForm->login();
            if($bool){
                /** 成功返回 */
                $resultData['id'] = $loginForm->getBusiness()->getId();
                $resultData['auth_key'] = $loginForm->getBusiness()->getAuthKey();
                $resultData['status'] = $loginForm->getBusiness()->status;
                return $this->responseFormat($resultData);
            }
            /** 失败返回 */
            if($loginForm->errors){
                foreach($loginForm->errors as $key=>$info ){
                    $resultData[$key] = $info;
                }
            }
//            /** 成功返回 */
//            $resultData['id'] = $resetPasswordForm->getBusiness()->getId();
//            $resultData['auth_key'] = $resetPasswordForm->getBusiness()->getAuthKey();
//            $resultData['status'] = $resetPasswordForm->getBusiness()->status;
//            return $this->responseFormat($resultData);
        }else{
            /** 失败返回 */
            if ($resetPasswordForm->errors) {
                foreach ($resetPasswordForm->errors as $key => $info) {
                    $resultData[$key] = $info;
                }
            }
        }
        return $this->responseError($resultData);
    }

    /**
     * 更新密码
     * @param auth_key
     * @param oldpassword 原密码
     * @param newpassword  新密码
     * @param renewpassword 确认新密码
     */
    public function actionUpdatepassword()
    {
        /** 校验表单是否为空 */
        if(!$this->postData){
            return $this->responseError("参数信息为空.");
        }
        /** 验证身份 */
        $isGuest = Yii::$app->user->getIsGuest();
        /** 未登陆 */
        if($isGuest){
            return $this->responseError('当前用户未登陆.');
        }

        /** 查询Business */
        $business = Business::findIdentity(Yii::$app->user->getId());

        if(!$business){
            return $this->responseError('没有匹配到商家信息,请重新登陆.');
        }
        /** 校验auth_key */
        if($business->getAuthKey() == $this->postData['auth_key']){
            /** 校验密码 */
            $bool = $business->validatePassword($this->postData['oldpassword']);
            if($bool){
                /** 定义返回数据 */
                $resultData = array();
                /** 接收表单参数 */
                $resetPasswordForm = new ResetPasswordForm();
                $resetPasswordForm->account = $business['account'];
                $resetPasswordForm->code = '1234';
                $resetPasswordForm->password = $this->postData['newpassword'];
                $resetPasswordForm->repassword = $this->postData['renewpassword'];

                /** 重置密码 */
                $bool = $resetPasswordForm->resetPassword();
                if ($bool) {
                    /** 成功返回 */
                    $resultData['id'] = $business['id'];
                    $resultData['auth_key'] = $business['auth_key'];
                    return $this->responseFormat($resultData);
                }

                /** 失败返回 */
                if ($resetPasswordForm->errors) {
                    foreach ($resetPasswordForm->errors as $key => $info) {
                        $resultData[$key] = $info;
                    }
                }
                /** 重置失败 */
                return $this->responseError($resultData);
            }
            /** 密码校验失败 */
            return $this->responseError('oldpassword info is wrong.');
        }else{
            /** auth_key认证失败 */
            return $this->responseError('auth_key info is wrong.');
        }
    }

    /**
     * 修改账号
     * @param auth_key
     * @param password 原密码
     * @param newaccount  新账号
     * @param code 验证码
     */
    public function actionRestaccount()
    {
        /** 校验表单是否为空 */
        if(!$this->postData){
            return $this->responseError("参数信息为空.");
        }
        /** 验证身份 */
        $isGuest = Yii::$app->user->getIsGuest();
        /** 未登陆 */
        if($isGuest){
            return $this->responseError('当前用户未登陆.');
        }

        /** 查询Business */
        $business = Business::findIdentity(Yii::$app->user->getId());
        /** 校验auth_key */
        if($business->validateAuthKey($this->postData['auth_key'])){
            /** 校验密码 */
            $bool = $business->validatePassword($this->postData['password']);
            if($bool){
                /** 定义返回数据 */
                $resultData = array();
                /** 接收表单参数 */
                $registerForm = new RegisterForm();
                $registerForm->account = $this->postData['newaccount'];
                $registerForm->code = $this->postData['code'];
                $registerForm->password = $this->postData['password'];
                $registerForm->repassword = $this->postData['password'];
                /** 重置账号 */
                if($newbusiness = $registerForm->resetAccount($business)){
                    /** 成功返回 */
                    $resultData['id'] = $newbusiness->getId();
                    $resultData['auth_key'] = $newbusiness->getAuthKey();
                    return $this->responseFormat($resultData);
                }
                /** 失败返回 */
                if($registerForm->errors){
                    foreach($registerForm->errors as $key=>$info ){
                        $resultData[$key] = $info;
                    }
                }
                /** 重置失败 */
                return $this->responseError($resultData);
            }
            /** 密码校验失败 */
            return $this->responseError('oldpassword info is wrong.');
        }else{
            /** auth_key认证失败 */
            return $this->responseError('auth_key info is wrong.');
        }
    }

    /**
     * 登出
     */
    public function actionLogout()
    {
        /** 登出 */
        Yii::$app->user->logout();
        /** 定义返回数据 */
        $resultData = array();
        return $this->responseFormat($resultData);
    }
}